<template>
  <div class="content-box">
    <heading grade="1" style="margin: 0 0 20px;">{{isPreview ? '赛程预览': '赛程'}}</heading>
    <GroupSlider
      :value="activeGroup"
      :list="groupList"
      :slides="8"
      @change="handleChange"
      :height="'38px'">
      <template scope="scope">
        <p style="line-height:36px;">{{scope.groupName| groupName}}</p>
      </template>
    </GroupSlider>

    <DateSlider style="margin:20px 0 50px;"
      v-model="activeDate" 
      :list="dateList" 
      @change="handleCheck">
    </DateSlider>

    <div v-if="gameList.length">
      <place-group :list="placeList" v-model="selectedPlaceIdx" @change="handleSelect"/>
      <!--预览-->
      <ul class="match-list preview" v-if="isPreview">
        <li v-for="(item,$index) in gameList" class="match-item  clearfix" v-bind:class="{odd:$index%2==0}"
          :key="item.dateTime">
          <el-row style="float:none">
            <el-col :span="4">
              <p class="horizon">{{ new Date(item.startTime).format("yyyy-MM-dd hh:mm") }}</p>
            </el-col>
            <el-col :span="4" :offset="1">
              <p class="horizon">
                <span v-if="item.gradePage">{{Number(item.gradePage) - 1 | NumberToArab}}&nbsp;&nbsp;</span>第{{item.grade}}轮
              </p>
            </el-col>
            <el-col :span="4" :offset="1">
              <div class="fl host-team">
                  <p class="team-name hidden">{{item.hostUserName || '待定'}}</p>
              </div>
              <div class="fl no-margin">
                  <x-img :src="item.hostIconUrl || 'static/images/default-logo.png'"></x-img>
              </div>
            </el-col>
            <el-col :span="1" :offset="1">
              <p class="match-vers horizon">vs</p>
            </el-col>
            <el-col :span="4" :offset="1">
              <div class="fl no-margin">
                <x-img :src="item.guestIconUrl || 'static/images/default-logo.png'"></x-img>
              </div>
              <div class="fl guest-team">
                <p class="team-name hidden">{{item.guestUserName || '待定'}}</p>
              </div>
            </el-col>
          </el-row>
        </li>
      </ul>
      <!--编辑-->
      <ul class="match-list small" v-else>
        <li v-for="(item,$index) in gameList" class="match-item  clearfix" 
            v-bind:class="{odd:$index%2==0}"
            :key="item">
            <el-row>
              <el-col :span="4" class="match-date">
                <p>{{new Date(item.startTime).format("yyyy-MM-dd hh:mm")}}</p>
                <p>第{{item.grade}}轮</p>
              </el-col>
              <el-col :span="2" class="logo">
                  <x-img  :src="item.hostIconUrl"/>
              </el-col>
              <el-col :span="4">
                <div class="team">
                  <div class="host tm-name">
                    <p v-if="item.hostUserName || item.hostUserId">{{item.hostUserName || item.hostUserId !== 'pending' ? item.hostUserId:'待定' }}</p>
                    <p v-else>待定</p>
                    <template v-if="item.status==6 && Number(item.homeScore)==0">
                      <div class="giveup">已弃权</div>
                    </template>                          
                    <el-button type="link" v-if="item.hostUserName && (!item.homeScore) && item.status!==4 && item.status!==6"
                      @click="giveUp($event, item,'host')">弃权</el-button>
                  </div>
                </div>
              </el-col>                  
              <el-col :span="3">
                <div class="match-vs">
                  <p v-if="!item.homeScore && (!item.guestScore)" class="match-vers">vs</p>
                  <p v-if="item.end|| item.guestScore" class="match-vers">{{item.homeScore}}:{{item.guestScore}}</p>
                  <el-button style="line-height:19px;" type="link" v-if="!item.homeScore && item.status!==4 && item.status!==6" 
                      @click="openScore(item)">录入比分</el-button>
                </div>
              </el-col>
              <el-col :span="2"  class="logo">
                  <x-img :src="item.guestIconUrl" />
              </el-col>
              <el-col :span="4">
                <div class="team">
                  <div class="tm-name">
                    <p v-if="item.guestUserName || item.guestUserId">{{item.guestUserName || item.guestUserId !== 'pending' ? item.guestUserId: '待定'}}</p>
                    <p v-else>待定</p>
                    <template v-if="item.status==6 && item.guestScore==0">
                      <div class="giveup">已弃权</div>
                    </template> 
                    <el-button v-if="item.guestUserName && (!item.homeScore) && item.status!==4 && item.status!==6" 
                      type="link"  @click="giveUp($event, item,'guest')">弃权</el-button>
                  </div>
                </div>
              </el-col>
              <el-col :span="5">
                <!--status: 0、初始化（2轮以上赛事默认使用），1、待比赛，2、已结束，3、延迟比赛，4、取消比赛，5轮空-->
                <div v-if="item.status!==4 &&  item.status!==6">
                  <el-button v-show="!item.homeScore" class="tiny" size="small" @click="editGame(item)">编辑比赛</el-button>
                  <el-button v-show="!item.homeScore" class="tiny" size="small" @click="showCancel(item)">取消比赛</el-button>      
                  <!-- && (playRound - item.grade) > 1 -->                                    
                </div>
                <div v-if="item.status==4">
                  <span  class="canceled">已取消</span>
                </div>
                <div v-if="item.status==6">
                  <template v-if="item.remark">
                    <span class="canceled">{{item.remark}}</span>
                  </template>
                  <template v-else>
                    <span class="canceled" v-if="item.homeScore==0">主队弃权</span>
                    <span class="canceled" v-if="item.guestScore==0">客队弃权</span>
                  </template>                      
                </div>
              </el-col>
            </el-row>                
        </li>
      </ul>
    </div>

    <div v-else>没有比赛</div>

    <div class="button-box" v-if="isPreview">            
      <el-button type="primary" @click="$router.go(-1)">返回编辑</el-button>
      <el-button @click="generate()">生成赛程</el-button>
    </div>

    <div v-else>
      <heading class="title" grade="1">淘汰赛晋级表 
        <small v-if="playRound>2" v-bind:class="{active:isSemifinal==false}" @click="isSemifinal = false">大签表</small> 
        <small v-bind:class="{active:isSemifinal==true}"  @click="isSemifinal = true"
          v-if="playRound==7 || playRound==6 || playRound==5 || playRound==2" >
          半决赛
        </small>
      </heading>

      
      <template v-if="bigTableVisible && !isSemifinal">
        <div v-if="zoneNumber > 1">
          <ul class="clearfix">
            <li class="area" v-bind:class="{active:index == areaIndex}" @click="handleActive(index)"
              v-for="(item,index) in 4" :key="item" >
              {{index+1}}/4区
            </li>
          </ul>
        </div>       
        <ul class="round clearfix">
          <li class="round" v-for="item in roundList" :key="item" v-bind:style="{width: (1/roundList.length *100)+'%'}">
            {{item}}
          </li>
        </ul>

        <div class="clearfix check-tb">        
          <ul class="fl" v-for="item in dataList" :key="item" v-bind:style="{width: (1/dataList.length *100)+'%'}">
            <li v-for="game in item.matchScheduleResp" :key="game.id" class="relative game-item">
              <el-row>
                <el-col :span="24" class="center">
                  <div class="clearfix player-item" v-if="game.hostUserId">
                    <span class="player hidden">
                      {{game.hostUserName || (game.hostUserId == 'pending' ? '待定' : game.hostUserId) }}
                    </span>
                  </div>
                  <p class="vs" v-if="game.hostUserId && game.guestUserId && (!game.homeScore) && game.status==1">vs</p>
                  <p class="cancel" v-if="game.status == 4">已取消</p>
                  <p class="vs score" v-if="game.homeScore && game.guestScore">{{game.homeScore}} - {{game.guestScore}}</p>
                  <div class="clearfix player-item" v-if="game.guestUserId">
                    <span class="player hidden" 
                      v-bind:class="{champion:item.grade == playRound && (Number(game.homeScore) < Number(game.guestScore)) }">
                      {{game.guestUserName || (game.guestUserId == 'pending' ? '待定' : game.guestUserId)}}
                    </span>
                  </div>                
                </el-col>      
              </el-row>
            </li>
          </ul>
        </div>
      </template>

      <template v-else>      
        <semifinal  
          :dataList="semiList"
          v-on:scoreWrite="openScore">
        </semifinal>        
      </template>
    </div>

    <!--录入大比分弹框-->
      <Dialog
        :visible="scoreVisible"
        :title="'请输入最终比分'"
        :cancelText="'取消'"
        :sureText="'确认'"
        v-on:cancel="closeScore()"
        v-on:confirm="checkPoint()"
        v-on:close="closeScore()">
        <div class="relative">
          <div style="margin-bottom:10px;">
            <label class="game-name hidden">{{game.hostUserName || game.hostUserId}}</label>
            <el-input class="score-input" v-model="homeScore" :maxlength="3">
              <template slot="append">分</template>
            </el-input>
          </div>
          <div>
            <label class="game-name hidden">{{game.guestUserName || game.guestUserId}}</label>
            <el-input class="score-input" v-model="guestScore" :maxlength="3">
              <template slot="append">分</template>
            </el-input>
          </div>
          <el-popover
            class="pop-over"
            ref="popover5"
            placement="top"
            width="200"
            v-model="popVisible">
            <p class="warnning">比分一经录入不能再次修改，是否确认录入？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="popVisible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="scoreWrite()">确定</el-button>
            </div>        
          </el-popover>
        </div>
      </Dialog>

    <!-- 取消比赛弹框 --> 
      <Dialog 
        :visible="cancelVisible"
        :title="'请选择取消比赛的原因'"
        :cancelText="'取消'"
        :sureText="'确认'"
        v-on:cancel="hideMessageBox()"
        v-on:confirm="cancelGame()"
        v-on:close="hideMessageBox()">
        <el-radio-group v-model="cancelCase">
          <el-radio v-for="item in cancelOptions" :key="item.value" class="radio" :label="item.value">{{item.label}}</el-radio>
        </el-radio-group>
        <el-row style="margin-top:10px;">
          <el-col :span="3">
            <label>备注</label>
          </el-col>
          <el-col :span="21">
            <el-input  type="textarea" :rows="2"  placeholder="请输入备注"  v-model="remark">
            </el-input>
          </el-col>
        </el-row>  
      </Dialog>

      
  </div>  
</template>

<script>
import Api from 'api/race'
import GroupSlider from '../components/GroupSlider'
import Semifinal from './components/Semifinal'
import DateSlider from './components/DateSlider'
import PlaceGroup from './components/PlaceGroup'
import Dialog from '../components/Dialog'
import {knockout, cloneObj, filterPlace} from 'utils' // eslint-disable-line
import {mapGetters} from 'vuex'
export default {
  components: {
    Semifinal,
    DateSlider,
    PlaceGroup,
    Dialog,
    GroupSlider
  },
  computed: {
    ...mapGetters({
      race_detail: 'race_detail'
    }),
    isPreview () {
      return this.$route.path.indexOf('schedulepre') > -1
    },
    groupGrade () {
      let n = 0
      for (let d in this.firstGroup.schedules) {
        let day = this.firstGroup.schedules[d]
        if (day.length) {
          day.forEach(g => {
            if (g.grade > n) {
              n = g.grade
            }
          })
        }
      }
      return n
    }
  },
  created () {
    this.getScheduleInfo()
    !this.isPreview && this.getDrawData()
  },
  data () {
    return {
      bigTableVisible: false,
      isSemifinal: false, // 是否为半决赛
      roundList: [], // 轮次标题列表
      semiList: [], // 半决赛列表
      areaIndex: 0,
      playRound: 2, // 淘汰赛轮数
      scoreVisible: false,
      cancelVisible: false,
      popVisible: false,
      homeScore: '',
      guestScore: '',
      activeGroup: {},
      groupList: [],
      firstGroup: {},
      activeDate: {},
      dataList: [], // 签表
      dateList: [], // 日期列表
      selectedPlaceIdx: {},
      placeList: [], // 场地列表
      gameList: [], // 比赛列表
      canceledGame: {},
      cancelCase: 0, // 取消原因
      remark: '',  // 备注
      cancelOptions: [
        {label: '天气不好', value: 0},
        {label: '场地安排原因', value: 1},
        {label: '其他', value: 2}
      ],
      game: {},
      checkTableList: []
    }
  },
  methods: {
    resetData (list) {
      if (!list) {
        this.placeList = []
        this.gameList = []
      } else {
        this.placeList = filterPlace(list)
        this.selectedPlaceIdx = 0
        this.gameList = this.placeList[this.selectedPlaceIdx].data
      }
    },
    getScheduleInfo () {
      Api.getCupScheduleInfo({matchId: this.$route.query.id}).then((res) => {
        let result = []
        this.firstGroup = res.data['A']
        result.push({
          groupName: 'all',
          nav: res.data['all'].nav,
          schedules: res.data['all'].schedules
        })
        for (let x in res.data) {
          if (x != 'knockout' && x != 'all') { // eslint-disable-line
            result.push({
              groupName: x,
              nav: res.data[x].nav,
              schedules: res.data[x].schedules
            })
          }
        }
        result.push({
          groupName: 'knockout',
          nav: res.data['knockout'].nav,
          schedules: res.data['knockout'].schedules
        })
        this.groupList = result
        this.activeGroup = this.groupList[0]
        this.dateList = this.activeGroup.nav
        this.activeDate = this.dateList[0]
        let gameList = this.activeGroup.schedules[this.activeDate.scheduleDate]
        this.resetData(gameList)
      })
    },
    // 分组点击事件
    handleChange (group) {
      this.activeGroup = group
      this.dateList = group.nav
      this.activeDate = this.dateList[0]
      let gameList = this.activeGroup.schedules[this.activeDate.scheduleDate]
      this.resetData(gameList)
    },
    // 日期点击事件
    handleCheck (date) {
      this.activeDate = date
      let gameList = this.activeGroup.schedules[date.scheduleDate]
      this.resetData(gameList)
    },
    // 场地点击事件
    handleSelect (i) {
      let index = typeof i === 'number' ? i : Number(i.placeNumber)
      index = index > this.placeList.length - 1 ? 0 : index
      this.gameList = this.placeList[index].data
    },
    hideMessageBox () {
      this.cancelVisible = false
    },
    // 取消比赛
    cancelGame () {
      Api.matchCancel({
        id: this.canceledGame.id,
        cancleCase: this.cancelOptions[this.cancelCase].label,
        remark: this.remark
      }, {context: this}).then((res) => {
        this.canceledGame.status = 4
        this.remark = ''
        this.$message({
          type: 'success',
          message: '取消成功!'
        })
        this.hideMessageBox()
        let ind = this.dateList.indexOf(this.activeDate)
        if (ind >= 0) {
          this.dateList[ind].matchNumber--
        }
        this.getDrawData()
      }).catch((err) => {
        this.$message({
          type: 'warning',
          message: err.msg
        })
        this.hideMessageBox()
      })
    },
    // 弹出取消比赛弹框
    showCancel (item) {
      this.canceledGame = item
      this.cancelVisible = true
    },
    // 进入编辑比赛页面
    editGame (item) {
      if (!item.hostUserName) {
        item.hostUserName = '待定'
      }
      if (!item.guestUserName) {
        item.guestUserName = '待定'
      }
      this.$store.commit('MATCH_DETAIL', item)
      this.$router.push({
        path: '/race/detail/manage/matchedit',
        query: {
          id: this.$route.query.id,
          gameId: item.id,
          isRun: this.$route.query.isRun,
          tasktype: this.$route.query.tasktype
        }
      })
    },
    closeScore () {
      this.scoreVisible = false
      this.homeScore = ''
      this.guestScore = ''
      this.popVisible = false
    },
    // 打开录入比分弹框
    openScore (item) {
      this.scoreVisible = true
      this.game = item
    },
    checkPoint () {
      if ((Number.isInteger(parseInt(this.homeScore))) && (Number.isInteger(parseInt(this.guestScore))) &&
        parseInt(this.homeScore) >= 0 && parseInt(this.guestScore) >= 0) {
        this.popVisible = true
      } else {
        this.$message({
          type: 'error',
          message: '比分请输入非负整数'
        })
        return false
      }
    },
    // 录入比分
    scoreWrite () {
      if ((Number.isInteger(parseInt(this.homeScore))) && (Number.isInteger(parseInt(this.guestScore))) &&
        parseInt(this.homeScore) >= 0 && parseInt(this.guestScore) >= 0) {
        Api.scoreWrite({
          id: this.game.id,
          hostScores: Number(this.homeScore),
          guestScores: Number(this.guestScore),
          cupScoreVO: []
        }, {context: event.target}).then((res) => {
          setTimeout(() => {
            this.game.homeScore = this.homeScore
            this.game.guestScore = this.guestScore
            if (this.groupGrade === this.game.grade) { // 小组最后一轮
              this.getDrawData()
            }
            this.closeScore()
          }, 100)
        }).catch((err) => {
          this.$message({
            type: 'warning',
            message: err.msg
          })
          this.popVisible = false
        })
      } else {
        this.$message({
          type: 'error',
          message: '比分请输入非负整数'
        })
        return false
      }
    },
    // 比赛弃权
    giveUp (event, item, team) {
      let isHost = team === 'host' ? 1 : 0
      let text = isHost ? '主队：' + item.hostUserName : '客队：' + item.guestUserName
      this.$confirm('确认 ' + text + ' 弃权?', '提示', {
        type: 'warning'
      }).then(() => {
        Api.matchGiveup({
          id: item.id,
          hostUserId: item.hostUserId,
          guestUserId: item.guestUserId,
          status: 6,  // 4：取消比赛，5：轮空，6：弃权
          result: isHost ? 3 : 4 // 3：主队弃权，4：客队弃权
        }, {context: event.target}).then((res) => {
          item.end = 1
          item.status = 6
          item.homeScore = res.data.hostScore
          item.guestScore = res.data.guestScore
        }).catch((err) => {
          this.$message({
            type: 'warning',
            message: err.msg
          })
        })
      }).catch(() => {
      })
    },
    // 生成赛程
    generate () {
      this.$confirm('确定要生成赛程？', '提示', {
        type: 'warning'
      }).then(() => {
        Api.generateSchedule({matchId: this.$route.query.id}, {context: this}).then((res) => {
          this.$router.push({ // 杯赛
            path: '/race/detail/manage/schedulecup',
            query: this.$route.query
          })
        }).catch((err) => {
          this.$message({
            type: 'warn',
            message: err.msg
          })
        })
      })
    },
    // 获取签表数据
    getDrawData () {
      Api.getDrawData({matchId: this.$route.query.id}).then((res) => {
        this.zoneNumber = res.data.length
        if (this.zoneNumber > 1) { // 有分区,球队>=32
          this.checkTableList = res.data
          if (res.data[4]) {
            this.playRound = res.data[4].grades[1].grade
            this.semiList = res.data[4].grades
          }
        } else {
          this.playRound = res.data[0].grades.length
          if (this.playRound === 2) { // 4支
            this.semiList = res.data[0].grades
            this.isSemifinal = true
          }
          if (this.playRound === 3) { // 8支
            this.isSemifinal = false
          }
          if (this.playRound === 4) { // 16支
            this.semiList = res.data[0].grades.filter(item => {
              return item.grade > 2
            })
          }
        }
        this.bigTableVisible = this.playRound > 2
        this.dataList = res.data[this.areaIndex].grades
        this.handleSort()
        this.calcRound()
      })
    },
    handleSort () {
      this.dataList.sort(function (a, b) {
        return a.grade - b.grade
      })
    },
    // 计算有多少轮
    calcRound () {
      this.roundList = knockout(this.playRound)
    },
    // 选中分区tab事件
    handleActive (index) {
      this.areaIndex = index
      this.dataList = this.checkTableList[index].grades
      this.handleSort()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/scheduleCup.scss';
@import '../../styles/knockout.scss';   
.preview{
  font-size: 12px;
}
.team-name{
  width:60px;
  line-height: 38px;
}
.horizon{
  line-height: 38px!important;
}
.no-margin{
  img{
    margin-left: 0;
    margin-right: 0;
  }
}
.host-team{
  margin-right:20px;
}
.guest-team{
  margin-left: 20px;
}
</style>
<style lang="scss">
.pop-over{
  .el-popover{
    right: 20px;
    top: 68px;
    display: block;
  }
  .warnning{
    line-height: 20px;
    margin-bottom: 5px;
    font-size: 14px;
  }
}
</style>
